package com.ttxs.fileformathandling.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ttxs.apicommon.model.entity.Api;
import com.ttxs.apicommon.model.entity.UserApiInfo;
import com.ttxs.fileformathandling.annotation.AuthCheck;
import com.ttxs.fileformathandling.common.BaseResponse;
import com.ttxs.fileformathandling.common.ErrorCode;
import com.ttxs.fileformathandling.common.ResultUtils;
import com.ttxs.fileformathandling.constant.UserConstant;
import com.ttxs.fileformathandling.exception.BusinessException;
import com.ttxs.fileformathandling.mapper.UserApiInfoMapper;
import com.ttxs.fileformathandling.model.vo.UserApiInfoVO;
import com.ttxs.fileformathandling.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分析各个接口调用次数
 *
 * @author cwt
 * @version 1.0
 */

@RestController
@RequestMapping("/analysis")
@Slf4j
public class analyzeController {
    @Resource
    private UserApiInfoMapper userApiInfoMapper;

    @Resource
    private ApiService apiService;

    @GetMapping("/top/invoke/api")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<UserApiInfoVO>> listTopInvokeApi() {
        List<UserApiInfo> userApiInfoList = userApiInfoMapper.listTopInvokeApi(10);
        //根据api id分组
        Map<Long, List<UserApiInfo>> apiIdObjMap = userApiInfoList.stream().collect(Collectors.groupingBy(UserApiInfo::getApiId));
        //根据id 将各个api的信息查出
        QueryWrapper<Api> apiQueryWrapper = new QueryWrapper<>();
        apiQueryWrapper.in("id", apiIdObjMap.keySet());
        List<Api> apiList = apiService.list(apiQueryWrapper);
        if (CollectionUtils.isEmpty(apiList)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "暂无数据");
        }

        List<UserApiInfoVO> apiInfoVOList = apiList.stream().map(api -> {
            UserApiInfoVO userApiInfoVO = new UserApiInfoVO();
            BeanUtils.copyProperties(api, userApiInfoVO);
            int totalNum = apiIdObjMap.get(api.getId()).get(0).getTotalNum();
            userApiInfoVO.setTotalNum(totalNum);
            return userApiInfoVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(apiInfoVOList);
    }
}
